<template>
  <div class="statistics">
    <div v-if="loading" class="loading">加载中...</div>

    <div v-if="error" class="error">{{ error }}</div>

    <div v-if="totalDraws === 0 && !loading" class="no-data">暂无统计数据</div>

    <div v-if="totalDraws > 0 && !loading">
      <p>共 {{ totalDraws }} 期数据</p>

      <div class="stats-container">
        <!-- 前区统计 - 横向表格 -->
        <div class="stat-section">
          <h4>前区统计 (出现次数前10)</h4>
          <table class="stats-table horizontal-table">
            <thead>
              <tr>
                <th>项目</th>
                <template v-for="item in frontStats" :key="item.num">
                  <th>{{ item.num }}</th>
                </template>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td>出现次数</td>
                <template v-for="item in frontStats" :key="`count-${item.num}`">
                  <td>{{ item.count }}</td>
                </template>
              </tr>
              <tr>
                <td>出现概率</td>
                <template v-for="item in frontStats" :key="`rate-${item.num}`">
                  <td>{{ item.rate }}%</td>
                </template>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 后区统计 - 横向表格（仅当有后区时显示） -->
        <div v-if="hasBack" class="stat-section">
          <h4>后区统计</h4>
          <table class="stats-table horizontal-table">
            <thead>
              <tr>
                <th>项目</th>
                <template v-for="item in backStats" :key="item.num">
                  <th>{{ item.num }}</th>
                </template>
              </tr>
            </thead>
            <tbody>
              <tr>
                <td>出现次数</td>
                <template v-for="item in backStats" :key="`count-${item.num}`">
                  <td>{{ item.count }}</td>
                </template>
              </tr>
              <tr>
                <td>出现概率</td>
                <template v-for="item in backStats" :key="`rate-${item.num}`">
                  <td>{{ item.rate }}%</td>
                </template>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { getStatistics } from '../api/api'

const props = defineProps({
  type: {
    type: String,
    required: true
  },
  name: {
    type: String,
    required: true
  },
  hasBack: {
    type: Boolean,
    default: true
  }
})

// 状态管理
const frontStats = ref([])
const backStats = ref([])
const totalDraws = ref(0)
const loading = ref(false)
const error = ref('')

// 获取统计数据
const fetchStatistics = async () => {
  loading.value = true
  error.value = ''

  try {
    const result = await getStatistics(props.type)

    if (result && result.code === 20000) {
      const { frontCounts, backCounts, totalDraws: draws, totalFrontNums, totalBackNums } = result.data

      totalDraws.value = draws

      // 处理前区统计 - 过滤索引为0的数据
      frontStats.value = Object.entries(frontCounts)
        .filter(([num]) => parseInt(num) !== 0) // 过滤掉索引为0的数据
        .map(([num, count]) => ({
          num: parseInt(num),
          count,
          rate: ((count / totalFrontNums) * 100).toFixed(2)
        }))
        .sort((a, b) => b.count - a.count)
        .slice(0, 10)

      // 处理后区统计 - 只有有后区时才处理
      if (props.hasBack) {
        backStats.value = Object.entries(backCounts)
          .filter(([num]) => parseInt(num) !== 0) // 过滤掉索引为0的数据
          .map(([num, count]) => ({
            num: parseInt(num),
            count,
            rate: ((count / totalBackNums) * 100).toFixed(2)
          }))
          .sort((a, b) => b.count - a.count)
      } else {
        backStats.value = []
      }
    } else {
      error.value = '获取统计数据失败'
    }
  } catch (err) {
    error.value = '网络错误，请稍后重试'
    console.error(err)
  } finally {
    loading.value = false
  }
}

// 监听类型和后区状态变化
watch([() => props.type, () => props.hasBack], fetchStatistics)

// 初始化
onMounted(fetchStatistics)
</script>

<style scoped>
.statistics {
  max-width: 1200px;
  margin: 0 auto;
  padding: 1rem;
}

.stats-container {
  display: flex;
  flex-direction: column;
  gap: 2rem;
  margin-top: 1rem;
}

.stat-section {
  width: 100%;
  overflow-x: auto;
}

.stats-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 1rem;
}

.stats-table th,
.stats-table td {
  padding: 0.8rem;
  text-align: center;
  border: 1px solid #eee;
}

.stats-table th {
  background-color: #f5f5f5;
  font-weight: bold;
  white-space: nowrap;
}

/* 横向表格特殊样式 */
.horizontal-table th:first-child,
.horizontal-table td:first-child {
  background-color: #f5f5f5;
  font-weight: bold;
  position: sticky;
  left: 0;
  z-index: 1;
}

.loading,
.no-data,
.error {
  text-align: center;
  padding: 2rem;
  color: #666;
}

.error {
  color: #ff4444;
}

h3,
h4 {
  text-align: center;
  margin: 1rem 0;
}
</style>